from django.db.models import F
from django.db.models.functions import Coalesce

from base.models import CustomSupplier
from points.models import HistoryPoint


def save_customer_history_point(customer_id):
    """保存历史信息"""
    customer = CustomSupplier.objects.filter(id=customer_id).first()
    data = {
        "customer_id": customer.id,
        "active_point": customer.active_point,
        "member_point": customer.member_point,
        "consume_point": customer.consume_point,
    }
    HistoryPoint.objects.create(**data)


def update_customer_points(customer_id, active_point, member_point):
    """修改客户积分"""
    save_customer_history_point(customer_id)

    CustomSupplier.objects.filter(id=customer_id)\
        .update(active_point=Coalesce(F("active_point"), 0) + active_point,
                member_point=Coalesce(F("member_point"), 0) + member_point)


def set_customer_vip(obj):
    """设置用户为vip"""
    customer = CustomSupplier.objects.filter(id=obj.customer_id).first()
    if customer.is_vip != 1:
        CustomSupplier.objects.filter(id=obj.customer_id).update(is_vip=1)


def update_customer_consume_points(customer_id, consume_point):
    """修改客户消费积分"""
    save_customer_history_point(customer_id)

    CustomSupplier.objects.filter(id=customer_id)\
        .update(consume_point=Coalesce(F("consume_point"), 0) + consume_point)


def update_customer_active_points(customer_id, active_point):
    """修改客户消费积分"""
    save_customer_history_point(customer_id)

    CustomSupplier.objects.filter(id=customer_id).update(active_point=Coalesce(F("active_point"), 0) + active_point)


def update_customer_member_points(customer_id, member_point):
    """修改客户消费积分"""
    save_customer_history_point(customer_id)

    CustomSupplier.objects.filter(id=customer_id).update(member_point=Coalesce(F("member_point"), 0) + member_point)

